export interface JwtPayload {
    /** 签发时间 */
    iat: number;
    /** 过期时间 */
    exp: number;
    /** 用户ID */
    sub: string;
    /** 其他自定义字段 */
    [key: string]: any;
}

const TOKEN_KEYS = {
    ACCESS_TOKEN: 'access_token',
    REFRESH_TOKEN: 'refresh_token'
} as const;



export default {
    /**解析token返回JWT payload数据 */
    parseJwt(token: string): JwtPayload | null {
        try {
            const base64Url = token.split('.')[1]
            const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
            const jsonPayload = decodeURIComponent(
                atob(base64)
                    .split('')
                    .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
                    .join(''),
            )
            return JSON.parse(jsonPayload)
        } catch (e) {
            console.error('Token parsing error:', e)
            return null
        }
    },
    isAuthenticate(): boolean {
        if(this.isAccessTokenValid())return true
        if(this.isRefreshTokenValid())return true
        return false
    },
    /**验证access token是否还处于有效期 */
    isAccessTokenValid(): boolean {
        const token = this.getAccessToken()
        if (!token) return false
        const payload = this.parseJwt(token)
        if (!payload) return false
        
        // 检查token是否过期
        const currentTime = Math.floor(Date.now() / 1000)
        return payload.exp > currentTime
    },

    /**验证refresh token是否有效 */
    isRefreshTokenValid(): boolean {
        const token = this.getRefreshToken()
        if (!token) return false
        const payload = this.parseJwt(token)
        if (!payload) return false
        
        // 检查refresh token是否过期
        const currentTime = Math.floor(Date.now() / 1000)
        return payload.exp > currentTime
    },

    /**管理token的保存 */
    setTokens(access_token: string, refresh_token: string): void {
        localStorage.setItem(TOKEN_KEYS.ACCESS_TOKEN, access_token)
        localStorage.setItem(TOKEN_KEYS.REFRESH_TOKEN, refresh_token)
    },

    /**管理token的清除 */
    removeTokens(): void {
        localStorage.removeItem(TOKEN_KEYS.ACCESS_TOKEN)
        localStorage.removeItem(TOKEN_KEYS.REFRESH_TOKEN)
    },

    /**获取保存的access token */
    getAccessToken(): string | null {
        return localStorage.getItem(TOKEN_KEYS.ACCESS_TOKEN)
    },

    /**获取保存的refresh token */
    getRefreshToken(): string | null {
        return localStorage.getItem(TOKEN_KEYS.REFRESH_TOKEN)
    }
}